"""
Main controller for the Worde blogging system
"""
__revision__ = "$Id: controllers.py 41 2007-02-16 21:08:04Z jens.persson $"
from turbogears import controllers, expose, validate, flash
from turbogears import identity, redirect, config, widgets, validators
from cherrypy import request, response

from worde import model, i18n
from worde import admin, templatehelpers, plugins
from worde.templatehelpers import get_config

plugins.find_plugins("%s/plugins" % config.config_defaults()["current_dir_uri"])


class Root(controllers.RootController):
    """
    The main controller
    """
    @expose(template="worde.templates.mainpage")
    def index(self):
        """
        Returns the first page, basicly all posts
        """
        posts = model.Post.select(model.Post.q.published == True,
                                  orderBy="-created")[:get_config("posts on frontpage")]
        return dict(posts=posts)


    class CommentFields(widgets.WidgetsList):
        """The fields used when creating posts"""
        title = widgets.TextField(validator=validators.NotEmpty(),
                                  attrs = {'size':30},
                                  label = _("title"))
        author = widgets.TextField(validator=validators.NotEmpty(),
                                   attrs = {'size':30},
                                   label = _("author"))
        authorlink = widgets.TextField(validator=validators.NotEmpty(),
                                       attrs = {'size':30},
                                       label = _("authorlink"))
        text = widgets.TextArea(validator=validators.NotEmpty(),
                                label = _("text"))

    commentform = widgets.TableForm(fields=CommentFields())

    @expose(template="worde.templates.postpage")
    def posts(self, *args, **kw):
        """
        Returns a post, or handles incomming comments
        """
        post = model.Post.select(model.Post.q.permalink == request.path)[0]
        if kw:
            @validate(form=self.commentform)
            def get_errors(self, tg_errors=None, **data):
                "Helper function to validate input"
                return tg_errors, data
            tg_errors, data = get_errors(self, **kw)

            if not tg_errors:
                comment = model.Comment(title=data["title"], text=data["text"], author=data["author"],
                                        authorlink=data["authorlink"], post = post)
                plugins.check_comment(comment, request)
                flash(_("Your comment have been added"))
                redirect(post.permalink)
            else:
                flash(_("Please fix the following errors: "))
        else:
            try:
                data = dict(author=identity.current.user.display_name)
            except AttributeError:
                data = {}

        comments = model.Comment.select(model.Comment.q.postID == post.id)
        return dict(post = post, comments = comments, commentform = self.commentform,
                    data = data)

    admin = admin.Admin()

    @expose(template="worde.templates.login")
    def login(self, forward_url=None, previous_url=None, *args, **kw):
        """
        Provide the user with a loginform
        """
        if not identity.current.anonymous \
            and identity.was_login_attempted() \
            and not identity.get_identity_errors():
            raise redirect(forward_url)

        forward_url = None
        previous_url = request.path

        if identity.was_login_attempted():
            msg = _("The credentials you supplied were not correct or "
                    "did not grant access to this resource.")
        elif identity.get_identity_errors():
            msg = _("You must provide your credentials before accessing "
                    "this resource.")
        else:
            msg = _("Please log in.")
            forward_url = request.headers.get("Referer", "/")

        response.status = 403
        return dict(message=msg, previous_url=previous_url, logging_in=True,
                    original_parameters=request.params,
                    forward_url=forward_url)

    @expose()
    def logout(self):
        """
        Logout the current user
        """
        identity.current.logout()
        raise redirect("/")